package net.sinmetal.twitcockpit.controller.twitter;

import net.sinmetal.twitcockpit.model.Robot;
import net.sinmetal.twitcockpit.service.RobotService;
import net.sinmetal.twitcockpit.twitter.Twitter4tc;
import net.sinmetal.twitcockpit.twitter.Twitter4tcFactory;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;

/**
 * AuthenticationCallbackController
 *
 * @author Sinmetal
 *
 */
public class CallbackController extends Controller {

    private RobotService robotService = new RobotService();

    /**
     * TwitterからのCallbackを受け取る
     */
    @Override
    public Navigation run() throws Exception {
        Twitter4tc twitter = new Twitter4tcFactory().getInstance();
        RequestToken requestToken = (RequestToken) sessionScope("requestToken");
        String verifier = requestScope("oauth_verifier");

        AccessToken accessToken =
            twitter.getOAuthAccessToken(requestToken, verifier);
        removeSessionScope("requestToken");

        Robot robot = Robot.getInstance(twitter.getUser(), accessToken);
        robotService.put(robot);
        return redirect("/");
    }
}
